# auth_routes.py
from flask import Blueprint, request, jsonify, session
from models import UserModel

auth_bp = Blueprint('auth', __name__)

# 需要在app.py中初始化后传入mysql实例
user_model = None

def init_auth(mysql_instance):
    global user_model
    user_model = UserModel(mysql_instance)

@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    if not data:
        return jsonify({'status': 'error', 'message': '缺少请求数据'}), 400

    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'status': 'error', 'message': '用户名和密码不能为空'}), 400

    try:
        account = user_model.get_user_by_credentials(username, password)

        if account:
            session.update({
                'loggedin': True,
                'id': account['id'],
                'username': account['username']
            })
            return jsonify({
                'status': 'success',
                'message': '登录成功',
                'user': account
            })
        return jsonify({'status': 'error', 'message': '用户名/密码错误'}), 401

    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': f'登录失败: {str(e)}'
        }), 500

@auth_bp.route('/user')
def user_info():
    if 'loggedin' in session:
        return jsonify({
            'status': 'success',
            'user': {
                'id': session['id'],
                'username': session['username']
            }
        })
    return jsonify({'status': 'error', 'message': '未登录'}), 401